package com.cxs.shopstore.controllers;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cxs.shopstore.models.Car;
import com.cxs.shopstore.service.CarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cxs
 * @since 2021-05-06
 */
@RestController
@RequestMapping("/car")
@SuppressWarnings("all")
public class CarController {
    @Autowired
    private CarService carService;
    @PostMapping("/addCar")
    public Map<String,Object> addCar(@RequestBody Car car){
        Map<String,Object> map = new HashMap<>();
        //判断是否已经加入购物车
        QueryWrapper<Car> wrapper = new QueryWrapper<>();
        wrapper.eq("car_good_id",car.getCarGoodId()).eq("car_user_id",car.getCarUserId());
        Car carObj = carService.getOne(wrapper);
        //已经加入购物车，在原基础上加数量
        if(carObj != null){
            car.setCarId(carObj.getCarId());
            car.setCarUserId(null);
            car.setCarGoodId(null);
            car.setCarNum(carObj.getCarNum() + car.getCarNum());
            car.setCarCreateTime(null);
            boolean update = carService.updateById(car);
            if(update){
                map.put("status",200);
                map.put("msg","加入成功");
            }else{
                map.put("status",500);
                map.put("msg","加入失败");
            }
        }else{
            //第一次加入
            car.setCarCreateTime(Calendar.getInstance().getTimeInMillis());
            boolean save = carService.save(car);
            if(save){
                map.put("status",200);
                map.put("msg","加入成功");
            }else{
                map.put("status",500);
                map.put("msg","加入失败");
            }
        }
        return map;
    }

    //获得所有购物车信息
    @GetMapping("/getCar/{userId}")
    public Map<String,Object> getCar(@PathVariable("userId") String userId){
        Map<String,Object> map = new HashMap<>();
        List<Car> carList = carService.getCarList(userId);
        map.put("status",200);
        map.put("data",carList);
        return map;
    }
    //删除一个
    @GetMapping("/deleteById/{carId}")
    public Map<String,Object> deleteById(@PathVariable("carId") String carId){
        Map<String,Object> map = new HashMap<>();
        boolean remove = carService.removeById(carId);
        if(remove){
            map.put("status",200);
        }else{
            map.put("status",500);
        }
        return map;
    }
    //删除所有
    @GetMapping("/deleteall")
    public Map<String,Object> deleteall(){
        Map<String,Object> map = new HashMap<>();
        boolean remove = carService.remove(null);
        if(remove){
            map.put("status",true);
        }else{
            map.put("status",false);
        }
        return map;
    }
}

